import { UserI } from "@/models/user";
import $api from "@/api/index";
import { SpecializationI } from "@/models/specialization";
import { APIPagination } from "@/models/common";
import { useCallback, useEffect, useState } from "react";
import { getUsers } from "@/api/users";
import { MonthPredictionI, PredictionI } from "@/models/prediction";
import { downloadBlob } from "@/pages/gantt/helpers";

export async function getPrediction(
  params?: URLSearchParams | null
): Promise<APIPagination<MonthPredictionI>> {
  const res = await $api.get(`api/service/month/`, {
    params,
  });

  return res.data;
}

export async function getPredictionById(
  id: string,
  params?: URLSearchParams | null
): Promise<MonthPredictionI> {
  const res = await $api.get(`api/service/month/${id}/`, {
    params,
  });

  return res.data;
}

export function usePrediction(
  params?: URLSearchParams | null
): [
  APIPagination<MonthPredictionI> | undefined,
  MonthPredictionI[] | undefined,
  boolean
] {
  const [isLoading, setLoading] = useState(false);
  const [data, setData] = useState<APIPagination<MonthPredictionI>>();

  const load = useCallback(async () => {
    // if (!params) return;
    setLoading(true);

    try {
      const r = await getPrediction(params);
      setData(r);
    } catch (error) {
      console.log({ error });
    } finally {
      setLoading(false);
    }
  }, [params]);

  useEffect(() => {
    load();
  }, [load]);

  return [data, data?.results, isLoading];
}

export async function generatePredictionReport(
  month: number,
  year: number
): Promise<void> {
  const res = await $api.post<Blob>(
    `api/service/predict_report/`,
    { month, year },
    {
      responseType: "arraybuffer",
    }
  );
  const blob = new Blob([res.data], {
    type: res.headers["content-type"],
  });

  downloadBlob(blob, `predict_report_${year}_${month}.xlsx`);
}

export async function approveMonthById(id: number): Promise<MonthPredictionI> {
  const res = await $api.post(`api/service/month/${id}/approve_month/`);

  return res.data;
}
